<template>
	<el-dialog v-model="visible" :close-on-click-modal="false" title="设备详情" draggable width="50%">
		<el-tabs v-loading="loading" v-model="state.activeName" @tab-click="handleClick">
			<el-tab-pane label="基本信息" name="base">
				<el-row :gutter="20" v-if="state.activeName === 'base'">
					<el-col :span="24">
						<el-descriptions :column="1" border :labelStyle="{ 'font-weight': 'bold' }">
							<el-descriptions-item label="设备ID">{{ state.deviceDetail.unitNo }}</el-descriptions-item>
							<el-descriptions-item label="产品Key">{{ state.deviceDetail.productKey }}</el-descriptions-item>
							<el-descriptions-item label="设备名称">{{ state.deviceDetail.deviceName }}</el-descriptions-item>
							<el-descriptions-item label="创建时间">
								{{ state.deviceDetail.createTime }}
							</el-descriptions-item>
							<el-descriptions-item label="设备状态">{{ state.deviceDetail.useStatus == 0 ? '未启用' : '启用' }}</el-descriptions-item>
							<el-descriptions-item label="最后上线时间">
								{{ state.deviceDetail.updateTime }}
							</el-descriptions-item>
							<el-descriptions-item label="所属位置">
								{{ state.deviceDetail.subareaCn }}
							</el-descriptions-item>
						</el-descriptions>
					</el-col>
				</el-row>
			</el-tab-pane>

			<el-tab-pane label="属性" name="property">
				<el-scrollbar style="height: 480px">
					<el-table v-if="state.activeName === 'property'" :data="state.properties" border v-loading="state.loading" style="width: 100%">
						<el-table-column prop="name" label="属性名" width="250">
							<template v-slot="scope"> {{ scope.row.name }}</template>
						</el-table-column>
						<el-table-column prop="identifier" label="标识符"> </el-table-column>
						<el-table-column prop="value" label="属性值">
							<template v-slot="scope">
								<span>{{ scope.row.value }}{{ scope.row.unit }} &nbsp;</span>
								<el-button @click="showPropertyHistory(scope.row)" size="small">历史</el-button>
							</template>
						</el-table-column>
						<el-table-column prop="occurred" label="修改时间">
							<template v-slot="scope">
								<span>{{ moment(Number(scope.row.timestamp)).format('YYYY-MM-DD HH:mm:ss') }} </span>
							</template>
						</el-table-column>
						<el-table-column label="可读写" width="80">
							<template v-slot="scope">
								<span v-if="scope.row.accessMode == 'r'">只读</span>
								<span v-else>可写</span>
								<!-- <el-tag v-if="scope.row.accessMode == 'r'" type="info" size="small" effect="plain">只读</el-tag>
								<el-button @click="showWriteProperty(scope.row)" v-if="scope.row.accessMode == 'rw'" size="small" type="success" plain>可写</el-button> -->
							</template>
						</el-table-column>
					</el-table>
					<div v-if="!!state.propertyHistory.name">
						<el-divider style="margin: 5px 0 10px 0"></el-divider>
						<el-row>
							<el-col :span="2">
								<h5>历史数据</h5>
							</el-col>
							<el-col :span="9">
								<el-date-picker
									v-model="state.historyTime"
									type="datetimerange"
									:picker-options="state.pickerOptions"
									range-separator="至"
									start-placeholder="开始日期"
									end-placeholder="结束日期"
									align="right"
									@change="timeRangeChange"
								>
								</el-date-picker>
							</el-col>
							<el-col :span="4">
								<!-- <el-radio-group v-model="state.dataType">
									<el-radio-button label="">无</el-radio-button>
									<el-radio-button label="stats">统计</el-radio-button>
								</el-radio-group> -->
							</el-col>
						</el-row>
						<PropertyChart
							v-if="state.propertyHistory.data.length != 0"
							:name="state.propertyHistory.name"
							:properties="state.propertyHistory.data"
						></PropertyChart>
						<el-empty v-else description="暂无数据" />
					</div>
				</el-scrollbar>
			</el-tab-pane>

			<el-tab-pane label="服务" name="service">
				<el-table v-if="state.activeName === 'service'" :data="state.services" border v-loading="state.loading" style="width: 100%">
					<el-table-column label="服务名称" width="180">
						<template v-slot="scope"> {{ scope.row.name }} </template>
					</el-table-column>
					<el-table-column prop="identifier" label="标识符" width="180"></el-table-column>
					<el-table-column label="操作" width="100">
						<template v-slot="scope">
							<el-button @click="showInvokeService(scope.row)" type="success" size="small" plain>调用</el-button>
						</template>
					</el-table-column>
					<el-table-column label="参数">
						<template v-slot="scope">
							<pre class="equipment-param">{{ scope.row.inputData }}</pre>
						</template>
					</el-table-column>
				</el-table>
			</el-tab-pane>

			<el-tab-pane label="日志" name="event">
				<el-form v-if="state.activeName === 'event'" :inline="true" :model="state.formInline" class="user-search">
					<el-form-item>
						<el-select v-model="state.formInline.type" placeholder="请选择日志类型">
							<el-option label="所有" value="" />
							<el-option label="状态" value="state" />
							<el-option label="事件" value="event" />
							<el-option label="属性" value="property" />
							<el-option label="服务" value="service" />
						</el-select>
					</el-form-item>
					<el-form-item label="搜索：">
						<el-input v-model="state.formInline.identifier" placeholder="日志识符" />
					</el-form-item>
					<el-form-item>
						<el-button type="primary" icon="Search" @click="logSearch">搜索</el-button>
					</el-form-item>
				</el-form>

				<el-table :data="state.events" border v-loading="state.loading" style="width: 100%">
					<el-table-column label="时间" width="180">
						<template v-slot="scope"> </template>
					</el-table-column>
					<el-table-column prop="type" label="类型" width="80" />
					<el-table-column prop="name" label="名称(标识符)" width="180" />
					<el-table-column label="内容">
						<template v-slot="scope">
							<!-- <pre class="equipment-param">{{ scope.row.content.data }}</pre> -->
						</template>
					</el-table-column>
				</el-table>
				<Pagination
					:data="state.formInline"
					:total="state.formInline.total"
					:page="state.formInline.pageNum"
					:limit="state.formInline.pageSize"
					@pagination="getEvents"
				/>
			</el-tab-pane>
		</el-tabs>
	</el-dialog>
	<el-dialog
		:title="state.title"
		v-model="state.propertyWriteFormVisible"
		width="40%"
		@close="closeDialog"
		:close-on-press-escape="false"
		:close-on-click-modal="false"
		append-to-body
		destroy-on-close
	>
		<el-form v-if="state.propertyWriteFormVisible" label-width="120px" :model="state.propertyWriteForm" ref="propertyWriteForm">
			<div style="display: none">
				<el-input v-model="state.propertyWriteForm.identifier" type="hidden" />
			</div>
			<el-form-item label="属性值" prop="value">
				<el-input v-model="state.propertyWriteForm.value" auto-complete="off" />
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="closeDialog">取消</el-button>
				<el-button type="primary" :loading="state.loading" class="title" @click="submitPropertyWriteForm">保存</el-button>
			</div>
		</template>
	</el-dialog>

	<el-dialog
		:title="state.title"
		v-model="state.serviceFormVisible"
		width="30%"
		@close="closeDialog"
		:close-on-press-escape="false"
		:close-on-click-modal="false"
		append-to-body
		destroy-on-close
	>
		<el-form v-if="state.serviceFormVisible" label-width="120px" :model="state.serviceForm" ref="serviceForm">
			<div>
				<el-input v-model="state.serviceForm.identifier" type="hidden" />
				<el-input v-model="state.serviceForm.productKey" type="hidden" />
				<el-input v-model="state.serviceForm.deviceName" type="hidden" />
			</div>
			<div v-if="state?.serviceForm?.params.length === 0">是否确认调用？</div>
			<el-form-item v-for="param in state.serviceForm.params" :key="param.identifier" :label="param.name + ':'" prop="params">
				<el-input v-if="param.dataType?.type === 'text'" v-model="param.value" auto-complete="off" />
				<el-input-number v-if="param.dataType?.type === 'int32' || param.dataType?.type === 'float'" v-model="param.value" auto-complete="off" />
				<el-radio-group v-if="param.dataType?.type === 'bool'" v-model="param.value">
					<el-radio v-for="(value, key, index) in param.dataType?.specs" :key="index" :label="key">{{ value }}</el-radio>
				</el-radio-group>
				<el-select v-if="param.dataType?.type === 'enum'" v-model="param.value" auto-complete="off">
					<el-option v-for="(value, key, index) in param.dataType?.specs" :key="index" :label="value" :value="key" />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="closeDialog">取消</el-button>
				<el-button type="primary" :loading="state.loading" class="title" @click="submitServiceForm">确认</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import { formatDate } from '/@/utils/formatTime';
import moment from 'moment';
import { getObj as getDevicesDetail, getDevicePropertyLogs, serviceInvoke } from '/@/api/basiciot/device/device';
// import {
// 	getDevicesDetail,
// 	devicesTagAdd,
// 	deviceSimulateSend,
// 	propertySet,
// 	deviceLogs,
// 	serviceInvoke,
// 	devicePropertyLogs,
// } from '/@/views/iot/equipment/api/devices.api';
import PropertyChart from './modules/PropertyChart.vue';
import { useMessage } from '/@/hooks/message';

const visible = ref(false);
const route = useRoute();
const router = useRouter();
const { id } = route.params;
const { showMap } = route.query || false;
const goBack = () => {
	router.back();
};

const formRef = ref();
const state = reactive<any>({
	loading: false,
	activeName: 'base',
	title: '',
	propertyWriteFormVisible: false,
	propertyWriteForm: {
		identifier: '',
		productKey: '',
		deviceName: '',
		value: '',
	},
	serviceFormVisible: false,
	serviceForm: {
		identifier: '',
		productKey: '',
		deviceName: '',
		params: [],
	},
	unitNo: '',
	deviceDetail: {},
	thingModel: null,
	properties: [],
	services: [],
	events: [],
	formInline: {
		type: '',
		identifier: '',
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	deviceLogs: [],
	typeMap: {
		lifetime: '生命周期',
		state: '设备状态',
		property: '属性',
		event: '事件',
		service: '服务',
	},
	propertyHistory: {
		name: '',
		data: [],
	},
	dataType: '',
	currHistoryProperty: {},
	historyTime: [new Date(new Date().getTime() - 24 * 3600 * 1000), new Date(new Date().getTime() + 24 * 3600 * 1000)],
	pickerOptions: {
		shortcuts: [
			{
				text: '最近1小时',
				onClick(picker) {
					const end = new Date();
					const start = new Date();
					start.setTime(start.getTime() - 3600 * 1000);
					picker.$emit('pick', [start, end]);
				},
			},
			{
				text: '最近6小时',
				onClick(picker) {
					const end = new Date();
					const start = new Date();
					start.setTime(start.getTime() - 3600 * 1000 * 6);
					picker.$emit('pick', [start, end]);
				},
			},
			{
				text: '最近1天',
				onClick(picker) {
					const end = new Date();
					const start = new Date();
					start.setTime(start.getTime() - 3600 * 1000 * 24);
					picker.$emit('pick', [start, end]);
				},
			},
			{
				text: '最近5天',
				onClick(picker) {
					const end = new Date();
					const start = new Date();
					start.setTime(start.getTime() - 3600 * 1000 * 24 * 5);
					picker.$emit('pick', [start, end]);
				},
			},
		],
	},
});
const getdata = () => {
	getDevicesDetail(state.unitNo).then((res) => {
		state.properties = res.data.properties;
		state.services = res.data.services;
		state.events = res.data.events;
	});
};
// 打开弹窗
const openDialog = (obj) => {
	visible.value = true;
	state.unitNo = obj.unitNo;
	state.deviceDetail = obj;
	state.activeName = 'base';
	getdata();
};

const logSearch = () => {
	state.formInline.pageNum = 1;
	getEvents({ page: 1, limit: 20 });
};
const getEvents = (e) => {
	state.formInline.pageNum = e.page;
	state.formInline.pageSize = e.limit;
	// deviceLogs({
	// 	unitNo: state.unitNo,
	// 	...state.formInline,
	// }).then((res) => {
	// 	state.formInline.total = res.data.total;
	// 	let logs: any[] = [];
	// 	res.data.rows.map((de) => {
	// 		let row = {
	// 			time: de.time,
	// 			type: state.typeMap[de.type],
	// 			name: '未知事件',
	// 			content: de,
	// 		};
	// 		logs.push(row);
	// 		if (!state.thingModel) return;
	// 		let modeEvents = state.thingModel.events;
	// 		if (modeEvents && modeEvents.length > 0) {
	// 			modeEvents.forEach((e) => {
	// 				if (de.identifier == e.identifier) {
	// 					row.name = e.name;
	// 					return;
	// 				}
	// 			});
	// 		}
	// 		let modeServices = state.thingModel.services;
	// 		if (de.type == 'property') {
	// 			if (de.identifier == 'set_reply') {
	// 				row.name = '设置回复';
	// 			} else if (de.identifier == 'report') {
	// 				row.name = '上报';
	// 			} else if (de.identifier == 'set') {
	// 				row.name = '设置';
	// 			}
	// 		} else if (de.type == 'state') {
	// 			if (de.identifier == 'online') {
	// 				row.name = '上线';
	// 			} else {
	// 				row.name = '下线';
	// 			}
	// 		} else if (de.type == 'lifetime') {
	// 			if (de.identifier == 'register') {
	// 				row.name = '注册';
	// 			}
	// 		} else if (modeServices && modeServices.length > 0) {
	// 			var ids = de.identifier.split('_reply');
	// 			modeServices.forEach((e) => {
	// 				if (ids[0] == e.identifier) {
	// 					row.name = e.name + (ids.length > 1 ? '回复' : '');
	// 					return;
	// 				}
	// 			});
	// 		}

	// 		row.name = row.name + '(' + de.identifier + ')';
	// 		return de;
	// 	});

	// 	state.events = logs;
	// });
};
const showPropertyHistory = (row) => {
	state.currHistoryProperty = row;
	refreshPropertyHistory();
};
const loading = ref(false);
const refreshPropertyHistory = () => {
	var end = state.historyTime[1];
	var start = state.historyTime[0];
	loading.value = true;
	getDevicePropertyLogs({
		unitNo: state.unitNo,
		field: state.currHistoryProperty.identifier,
		startTime: moment(start.getTime()).format('YYYY-MM-DD HH:mm:ss'),
		endTime: moment(end.getTime()).format('YYYY-MM-DD HH:mm:ss'),
	})
		.then((res) => {
			state.propertyHistory.name = state.currHistoryProperty.name;
			state.propertyHistory.data = res.data;
		})
		.finally(() => {
			loading.value = false;
		});
};
const timeRangeChange = () => {
	refreshPropertyHistory();
};
// const handleClick = (tab) => {
// 	tab.paneName == 'event' ? getEvents({ page: 1 }) : getdata();
// };
const showWriteProperty = (prop) => {
	state.propertyWriteFormVisible = true;
	state.title = '设置属性';
	state.propertyWriteForm.identifier = prop.identifier;
	state.propertyWriteForm.productKey = state.deviceDetail.productKey;
	state.propertyWriteForm.deviceName = state.deviceDetail.deviceName;
	state.propertyWriteForm.value = prop.value?.value ? prop.value.value : prop.value;
};
const submitPropertyWriteForm = () => {
	let form = state.propertyWriteForm;
	let prop = {};
	prop[form.identifier] = form.value;
	// propertySet({
	// 	unitNo: state.unitNo,
	// 	args: prop,
	// }).then((res) => {
	// 	if (res.code === 200) {
	// 		ElMessage({
	// 			type: 'success',
	// 			message: '操作成功',
	// 		});
	// 	} else {
	// 		ElMessage.error(res.message);
	// 	}
	// });
};
const showInvokeService = (service) => {
	state.serviceFormVisible = true;
	state.title = '服务调用';
	state.serviceForm.identifier = service.identifier;
	state.serviceForm.unitNo = state.deviceDetail.unitNo;
	let params: any[] = [];
	service.inputData.forEach((p) => {
		params.push({
			identifier: p.identifier,
			name: p.name,
			value: '',
			dataType: p.dataType,
		});
	});
	state.serviceForm.params = params;
};
const submitServiceForm = () => {
	let form = state.serviceForm;
	let param = {};
	let flag = true; //判断枚举类型的值时参数值选择是否为空
	state.serviceForm.params.forEach((p) => {
		console.log(p);
		if (p.value !== '') {
			param[p.identifier] = p.value;
		} else {
			flag = false;
			useMessage().error('请选择参数值');
		}
	});

	if (flag) {
		serviceInvoke({
			unitNo: state.unitNo,
			service: form.identifier,
			args: param,
			timestamp: moment().valueOf(),
		}).then((res) => {
			if (res.ok) {
				state.serviceFormVisible = false;
				useMessage().success('操作成功');
			} else {
				useMessage().error(err.msg);
			}
		});
	}
};

const closeDialog = () => {
	state.propertyWriteFormVisible = false;
	state.serviceFormVisible = false;
};
watch(visible, (val) => {
	if (val) {
		state.propertyHistory = {
			name: '',
			data: [],
		};
	}
});
logSearch();
// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style lang="scss" scoped>
.el-table {
	min-height: 240px;
	// max-height: 240px;
}
.box {
	padding: 15px;
	background: #fff;
}
.form-tips {
	font-size: 12px;
	line-height: 14px;
}
.equipment-param {
	max-height: 160px;
	overflow: hidden auto;
	word-wrap: break-word;
	white-space: pre-wrap;
	font-size: 12px;
	line-height: 14px;
}
</style>
